<template>
  <div class="container">
    <el-form
      style="margin-bottom:50px"
      ref="formDataRef"
      :model="formData"
      :rules="rules"
      label-width="80px"
    >
      <el-form-item label="学科名称" prop="subjectName" size="small">
        <el-input v-model="formData.subjectName"></el-input>
      </el-form-item>
      <el-form-item label="是否显示" prop="isFrontDisplay">
        <el-switch
          v-model="formData.isFrontDisplay"
          active-value="1"
          inactive-value="0"
          active-color="#13ce66"
          inactive-color="#ff4949"
        ></el-switch>
      </el-form-item>
    </el-form>
    <el-row type="flex" justify="center">
        <el-button @click="hCancel">取消</el-button>
        <el-button @click="submitSubject" type="primary">确定</el-button>
    </el-row>
  </div>
</template>

<script>
import { add, update } from '@/api/hmmm/subjects.js'
export default {
  props: {
    isEdit: {
      type: Boolean,
      required: true
    },
    backFormData: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      formData: {
        subjectName: '',
        isFrontDisplay: '1'
      },
      rules: {
        subjectName: [
          { required: true, message: '学科名称不能为空', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    if (this.isEdit) {
      this.formData = this.backFormData
    }
  },
  methods: {
    // 清空
    // 清空表单,校验规则
    hClean () {
      this.formData = {
        subjectName: '',
        isFrontDisplay: ''
      }
      this.$refs.formDataRef.resetFields()
    },
    // 点击取消
    hCancel () {
      this.$emit('close')
    },

    // 点击确定 添加||编辑
    // 做新增或修改提交
    submitSubject () {
      this.$refs.formDataRef.validate(async (valid) => {
        if (valid) {
          this.isEdit ? await this.doUpdate() : await this.doAdd()
          // 更新成功
          this.$emit('success')
        }
      })
    },

    // 做添加
    async doAdd () {
      try {
        const res = await add(this.formData)
        console.log(res)
      } catch (error) {
        this.$message.error(error.message)
      }

      // 解决添加后不跳转bug
      this.$emit('pageAdd')
    },

    // 做修改
    async doUpdate () {
      try {
        const res = await update({ ...this.formData })
        console.log(res)
      } catch (error) {
        this.$message.error(error.message)
      }
    }
  }
}
</script>

<style scoped lang='less'></style>
